﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services.Protocols;
using System.Web.UI;
using System.Web.UI.WebControls;
using MedicWeb.MedicService;
using Substitution = MedicWeb.MedicService.Substitution;

namespace MedicWeb.forms.Print.Edit {
    public partial class SubstitutionEdit : SessionPage {
        private Substitution substitution;

        protected void Page_Load(object sender, EventArgs e) {
            Form.Action = ResolveUrl("~/forms/Print/Edit/SubstitutionEdit.aspx");
            string id = Request.QueryString["id"];
            var ms = new MainService();
            if (id != null) {
                Form.Action += "?id=" + id;
                substitution = ms.LoadSubstitution(GetSession(), Convert.ToInt32(id));
            } else {
                substitution = new Substitution();
            }
            if (!IsPostBack) {
                tfAlias.Text = substitution.Alias;
                tfValue.Text = substitution.Value;
                tfReplace.Text = substitution.Replace;
                tfCondition.Text = substitution.Condition;
                comboContext.SelectedValue = substitution.Context;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e) {
            try {
                substitution.Value = tfValue.Text;
                substitution.Alias = tfAlias.Text;
                substitution.Replace = tfReplace.Text;
                substitution.Condition = tfCondition.Text;
                substitution.Context = comboContext.SelectedValue;
                var ms = new MainService();
                substitution = ms.SaveSubstitution(GetSession(), substitution);
                Session["success"] = "Изменения сохранены успешно";
            } catch (Exception ex) {
                if (ex.InnerException is SoapException
                    && ((SoapException)ex.InnerException).Detail.InnerText == "AuthorizationException") {
                    throw ex;
                } else {
                    Session["error"] = "Ошибка сохранения";
                }
            }
        }
    }
}